#!/bin/bash
set -e
set -o pipefail

# 获取脚本路径
CURRENT_DIR=$(cd $(dirname $0); pwd)
# 导入公共方法
source ${CURRENT_DIR}/common.sh
# 导入配置文件
source ${CURRENT_DIR}/config.cnf

# 安装前检查
function before_install_check(){
    comm_print_note "检测 ETCD 端口是否已存在"
    comm_check_port_occupied $etcd_cluster_port
    comm_check_port_occupied $ectd_client_port
}

# 安装ETCD
function install_dependent(){
    if [ $sys_type = "yum" ];then
        comm_print_note "使用yum安装..."
        yum install -y gcc python-devel epel-release
        yum install -y etcd
    else
        comm_print_note "使用apt安装..."
        apt-get install -y gcc python-dev
        apt-get install -y etcd
    fi
}

# 创建目录
function create_etcd_dir(){
    comm_print_note "授权etcd数据目录"
    mkdir -p ${pg_dir}/etcd
    chown etcd:etcd -R ${pg_dir}/etcd
}

# 确认配置参数 local_ip 是否正确
function check_local_ip(){
    local found=0
    # 由于未找到会返回非0
    set +e
    local found=$(ip a|grep $local_ip|wc -l)
    set -e
    if [ $found -eq 0 ];then
        comm_print_error "参数local_ip配置不正确，请确认！"
        exit 1
    fi
}

## ETCD_NAME: 默认设置为 etcd[IP最后一组值]
function etcd_install(){
    local array=(${etcd_cluster_ip//,/ })
    if [ ${#array[@]} -eq 1 ];then
        comm_print_note "安装单机版ETCD"
    elif [ ${#array[@]} -gt 2 ];then
        comm_print_note "安装集群版ETCD"
    else
        comm_print_note "请检查配置文件config中的etcd_cluster_ip值，请配置1个或2个以上"
    fi

    comm_print_note "开始安装..."
    install_dependent 
    comm_print_note "目录创建..."
    create_etcd_dir

    local etcd_name="etcd$(echo ${local_ip}|awk -F . '{print $4}')"

    comm_print_note "设置etcd集群配置文件"
    local etcd_initial_cluster=''
    local etcd_endpoints=''
    local num=0
    for ip in ${array[@]};
    do
        local ename="etcd$(echo ${ip}|awk -F . '{print $4}')"
        local etcd_endpoint="http://${ip}:${etcd_cluster_port}"
        local ecluster="${ename}=${etcd_endpoint}"
        if [ $num -eq 0 ];then
            etcd_initial_cluster=${ecluster}
            etcd_endpoints=${etcd_endpoint}
        else
            etcd_initial_cluster="${etcd_initial_cluster},${ecluster}"
            etcd_endpoints="${etcd_endpoints},${etcd_endpoint}"
        fi
        let num=num+1
    done

    cat > /etc/etcd/etcd.conf << EOF
ETCD_DATA_DIR="${pg_dir}/etcd/default.etcd"
ETCD_LISTEN_PEER_URLS="http://${local_ip}:${etcd_cluster_port}"
ETCD_LISTEN_CLIENT_URLS="http://localhost:${ectd_client_port},http://${local_ip}:${ectd_client_port}"
ETCD_NAME="${etcd_name}"
ETCD_INITIAL_ADVERTISE_PEER_URLS="http://${local_ip}:${etcd_cluster_port}"
ETCD_ADVERTISE_CLIENT_URLS="http://${local_ip}:2379"
ETCD_INITIAL_CLUSTER="${etcd_initial_cluster}"
ETCD_INITIAL_CLUSTER_TOKEN="etcd-cluster"
ETCD_INITIAL_CLUSTER_STATE="new"
EOF

    comm_print_note "启动etcd...，若为首个启动会等待其他加入后完成启动...因此需要同步安装组成集群的其他的etcd"
    start_etcd
    comm_print_note "配置 etcd 开机自启"
    etcd_systemctl_enable
    comm_print_note "设置etcd环境变量为v3，查看list与cluster 状态"
    etcd_status_check
}

# systemd启动
function start_etcd(){
    systemctl start etcd
    systemctl status etcd
}

# 设置开机自启
function etcd_systemctl_enable(){
    systemctl enable etcd
}

# 查看安装的ETCD相关健康状态
function etcd_status_check(){
    export ETCDCTL_API=3
    sleep 2
    etcdctl member list
    # etcdctl cluster-health
    etcdctl --endpoints=${etcd_endpoints} endpoint health
}

# 卸载ETCD
function uninstall_etcd(){
    comm_print_note "卸载etcd"
    if [ $sys_type = "yum" ];then
        yum remove etcd -y 
    else
        apt-get remove etcd
    fi
    comm_print_note "删除etcd相关目录   ${pg_dir}/etcd /var/lib/etcd"
    rm -rf ${pg_dir}/etcd
    rm -rf /var/lib/etcd
}

# 使用说明
usage () {
        cat <<EOF
Usage: $0 [OPTIONS]
  single                 安装单机版
  cluster                安装集群版本
  uninstall              卸载ETCD
  status                 查看状态
EOF
exit
}

# main 入口
command="${1}"
case "${command}" in
    "single" )
        comm_print_note "判断参数设置..."
        check_local_ip
        comm_print_note "安装单机版ETCD"
	    etcd_install "single"
    ;;
    "cluster" )
        comm_print_note "判断参数设置..."
        check_local_ip
        comm_print_note "安装集群版ETCD"
	    etcd_install "cluster"
    ;;
    "uninstall" )
        comm_print_note "卸载ETCD"
	    uninstall_etcd
    ;;
    "status" )
        comm_print_note "查看状态"
	    etcd_status_check
    ;;
    * )
        usage
    ;;
esac